package com.example.bighomework.utils;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class NetUtil {
    public static final String URL_WEATHER ="https://v1.yiketianqi.com/free/day?unescape=1&version=v9&appid=93952199&appsecret=36U61WDL";
    public static String doGet(String urlStr) {
        String result = "";
        HttpURLConnection connection = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
// 链接网络
        try {
            URL url = new URL(urlStr);
            connection =(HttpURLConnection) url.openConnection();
// 请求方式
            connection.setRequestMethod("GET");
// 请求超时
            connection.setConnectTimeout(5000);
// 从链接中读取天气数据流
            InputStream inputStream = connection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
// 将二进制数据送入缓冲区
            bufferedReader = new BufferedReader(inputStreamReader);
// 从缓冲区中一行行读取
            StringBuilder stringBuilder = new StringBuilder();
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            result = stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
    // 用get方法获取天气数据并拼接起来
    public static String getWeatherOfCity(String city) {
// public static final String URL_WEATHER = "https://v1.yiketianqi.com/free/day?unescape=1&version=v9&appid=93952199&appsecret=36U61WDL";
        String weatherUrl = URL_WEATHER + "&city=" + city;
        Log.d("result", "getWeatherOfCity: " + weatherUrl);
        String weatherResult = doGet(weatherUrl);
        Log.d("result", "result-- " + weatherResult);
        return weatherResult;
    }
}

